Hi, I keep trying to use transformable to store an array of strings with SwiftData, and I can see that it is activating the transformer, but it keeps saying that I am still using NSArray instead of NSData.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "category"; desired type = NSData; given type = Swift.__SwiftDeferredNSArray; value = (
yo,
gurt
).'
terminating due to uncaught exception of type NSException
CoreSimulator 1010.10 - Device: iPhone 16 18.0 (6879535B-3174-4025-AD37-ED06E60291AD) - Runtime: iOS 18.0 (22A3351) - DeviceType: iPhone 16
Message from debugger: killed
@Model
class MyModel: Identifiable, Equatable {
@Attribute(.transformable(by: StringArrayTransformer.self)) var category: [String]?
@Attribute(.transformable(by: StringArrayTransformer.self)) var amenities: [String]?
var image: String?
var parentChunck: HenricoPostDataChunk_V1?
init(category: [String]?, amenities: [String]?) {
self.category = category
self.amenities = amenities
}
}
class StringArrayTransformer: ValueTransformer {
override func transformedValue(_ value: Any?) -> Any? {
print(value)
guard let array = value as? [String] else { return nil }
let data = try? JSONSerialization.data(withJSONObject: array, options: [])
print(data)
return data
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
guard let data = value as? Data else { return nil }
let string = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String]
print(string)
return string
}
override class func transformedValueClass() -> AnyClass {
return NSData.self
}
override class func allowsReverseTransformation() -> Bool {
return true
}
static func register() {
print("regitsering")
ValueTransformer.setValueTransformer(StringArrayTransformer(), forName: .stringArrayTransformerName)
}
}
extension NSValueTransformerName {
static let stringArrayTransformerName = NSValueTransformerName("StringArrayTransformer")
}
SwiftData
RSS for tagSwiftData is an all-new framework for managing data within your apps. Models are described using regular Swift code, without the need for custom editors.
Posts under SwiftData tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Any idea what this message means? I assume it's coming from CloudKit, but the application seems to store and retrieve data properly.
I am struggling with exactly how to set up SwiftData relationships, beyond the single relationship model...
Let's say I have a school. Each school offers a set of classes. Each class is taught by one teacher and attended by several students. Teachers may teach more than one class, but only at one school. Similarly students may attend more than one class, but only at one school. Classes themselves may be offered at more than one school.
Can someone create a class for School, SchoolClass, Teacher, and Student with id, name, and relationships... I have tried it unsuccessfully about 10 different ways at this point.
My most recent is below... I am struggling getting beyond a school listing in the app, and I'll cross that bridge next. I am just wondering if all the trouble I am having is because I am not smart with the class definitions. And wondering if this is to complex for SwiftData and CoreData is the requirement.
This is not a real app, just my way of really trying to get a handle on Swift Data models and Navigation.
I am very new to Swift, and will take any and all suggestions with enthusiasm! Thanks for taking the time.
import Foundation
import SwiftData
@Model
class School: Identifiable {
var id: UUID = UUID()
var name: String
var mascot: String
var teachers: [Teacher]
var schoolClasses: [SchoolClass]
init (name: String, mascot: String = "", teachers: [Teacher] = [], schoolClasses: [SchoolClass] = []) {
self.name = name
self.mascot = mascot
self.teachers = teachers
}
class SchoolClass: Identifiable {
var id: UUID = UUID()
var name: String
var teacher: Teacher?
var students: [Student] = []
init (name: String, teacher: Teacher? = nil, students: [Student] = []) {
self.name = name
self.teacher = teacher
self.students = students
}
}
class Teacher: Identifiable {
var id: UUID = UUID()
var name: String
var tenured: Bool
var school: School?
var students: [Student] = []
init (name: String, tenured: Bool = false, students: [Student] = []) {
self.name = name
self.tenured = tenured
self.students = students
}
}
class Student: Identifiable {
var id: UUID = UUID()
var name: String
var grade: Int?
var teacher: Teacher?
init (name: String, grade: Int? = nil, teacher: Teacher? = nil) {
self.name = name
self.grade = grade
self.teacher = teacher
}
}
}
I tried to use the .deny deleteRule but it seems to have no effect.
The toolbar button adds an item with a relationship to a category to the context. Swiping on the category deletes the category even though an item is referencing the category. There is also no error thrown when saving the context. It is as if the deleteRule was not there.
For other deleteRules like .cascade, the provided sample code works as expected.
import SwiftUI
import SwiftData
@Model
class Category {
var name: String
@Relationship(deleteRule: .deny) var items: [Item] = []
init(name: String) {
self.name = name
}
}
@Model
class Item {
var name: String
var category: Category?
init(name: String, category: Category) {
self.name = name
self.category = category
}
}
struct DenyDeleteRule: View {
@Environment(\.modelContext) private var modelContext
@Query private var categories: [Category]
@Query private var items: [Item]
var body: some View {
List {
Section("Items") {
ForEach(items) { item in
Text(item.name)
}
}
Section("Categories") {
ForEach(categories) { category in
VStack(alignment: .leading) {
Text(category.name).bold()
ForEach(category.items) { item in
Text("• \(item.name)")
}
}
}
.onDelete(perform: deleteCategory)
}
}
.toolbar {
Button("Add Sample") {
let category = Category(name: "Sample")
let item = Item(name: "Test Item", category: category)
modelContext.insert(item)
}
}
}
func deleteCategory(at offsets: IndexSet) {
for index in offsets {
let category = categories[index]
modelContext.delete(category)
do {
try modelContext.save()
} catch {
print(error)
}
}
}
}
#Preview {
NavigationStack {
DenyDeleteRule()
}
.modelContainer(for: [Item.self, Category.self], inMemory: true)
}
I have a SwiftUI document-based app that for the sake of this discussion stores accounting information: chart of accounts, transactions, etc. Each document is backed by a SwiftData DB.
I'd like to incorporate search into the app so that users can find transactions matching certain criteria, so I went to Core Spotlight. Indexing & search within the app seem to work well.
The issue is that Spotlight APIs appear to be App based & not Document based. I can't find a way to separate Spotlight data by document.
I've tried having each document maintain a UUID as a document-specific identifier and include the identifier in every CSSearchableItem. When performing a query I filter the results with CSUserQueryContext.filterQueries that filter by the document identifier. That works to limit results to the specific file for search operations.
Index updates via CSSearchableIndexDelegate.reindex* methods seem to be App-centric. A user may have file #1 open, but the delegate is being asked to update CSSearchableItems for IDs in other files.
Is there a proper way to use Spotlight for in-app search with a document-based app?
Is there a way to keep Spotlight-indexed data local within the app & not make it available across the system? I.e. I'd like to search within the app only. System-level searches should not surface this data.
I'm building a SwiftUI app using SwiftData. In my app I have a Customer model with an optional codable structure Contact. Below is a simplified version of my model:
@Model class Customer {
var name: String = ""
var contact: Contact?
init(name: String, contact: Contact? = nil) {
self.name = name
self.contact = contact
}
struct Contact: Codable, Equatable {
var phone: String
var email: String
var allowSMS: Bool
}
}
I'm trying to query all the Customers that have a contact with @Query. For example:
@Query(filter: #Predicate<Customer> { customer in
customer.contact != nil
}) var customers: [Customer]
However no matter how I set the predicate I always get an error:
BugDemo crashed due to an uncaught exception NSInvalidArgumentException. Reason: keypath contact not found in entity Customer.
How can I fix this so that I'm able to filter by contact not nil in my Model?
I would like to have a SwiftData predicate that filters against an array of PersistentIdentifiers.
A trivial use case could filtering Posts by one or more Categories. This sounds like something that must be trivial to do.
When doing the following, however:
let categoryIds: [PersistentIdentifier] = categoryFilter.map { $0.id }
let pred = #Predicate<Post> {
if let catId = $0.category?.persistentModelID {
return categoryIds.contains(catId)
} else {
return false
}
}
The code compiles, but produces the following runtime exception (XCode 26 beta, iOS 26 simulator):
'NSInvalidArgumentException', reason: 'unimplemented SQL generation for predicate : (TERNARY(item != nil, item, nil) IN {}) (bad LHS)'
Strangely, the same code works if the array to filter against is an array of a primitive type, e.g. String or Int.
What is going wrong here and what could be a possible workaround?
If I set my build settings "default actor isolation" to MainActor, how do my @ModelActor actors and model classes need to look like ?
For now, I am creating instances of my @ModelActor actors and passing my modelContext container and processing all data there. Everything stays in this context. No models are transferred back to MainActor.
Now, after changing my project settings, I am getting a huge amount of warnings.
Do I need to set all my model classes to non-isolated and the @ModelActor actor as well?
Is there any new sample code to cover this topic ... did not find anything for now.
Thanks in advance, Marc
I have an iOS app using SwiftData with VersionedSchema. The schema is synchronized with an CloudKit container.
I previously introduced some model properties that I have now removed, as they are no longer needed. This results in the current schema version being identical to one of the previous ones (except for its version number).
This results in the following exception:
'NSInvalidArgumentException', reason: 'Duplicate version checksums across stages detected.'
So it looks like we cannot have a newer schema version with an identical content to an older schema version.
The intuitive way would be to re-add the old (identical) schema version to the end of the "schemas" list property in the SchemaMigrationPlan, in order to ****** that it is the newest one, and to add a migration stage back to it, thus:
public enum MySchemaMigrationPlan: SchemaMigrationPlan {
public static var schemas: [any VersionedSchema.Type] {
[
SchemaV100.self,
SchemaV101.self,
SchemaV100.self
]
}
public static var stages: [MigrationStage] {
[
migrateV100toV101,
migrateV101toV100
]
}
However, I am not sure if this is the right way to go, as previously, as I wanted to write unit tests for schema migration and rollback, I tried defining an inverse for each migration stage, so that I could trigger a migration and a rollback from a unit test, which resulted in an exception saying that it is not supported to downgrade a VersionedSchema.
I must admit that I solved the original problem by introducing a dummy model property that I will later remove. What would have been the correct approach?
I have encountered the following error and reduced my code to the minimum necessary to reliably reproduce this error.
Fatal error: Duplicate keys of type 'AnyHashable2' were found in a >Dictionary.
This usually means either that the type violates Hashable's >requirements, or
that members of such a dictionary were mutated after insertion.
It occurs when
instances of a swiftdata model are inserted (the error occurs reliably when inserting five or more instances. Fewer insertions seems to make the error either more rare or go away entirely) and
a Picker with .menu pickerStyle is present.
Any of the following changes prevents the error from occuring:
adding id = UUID() to the Item class
removing .tag(item) in the picker content
using any pickerStyle other than .menu
using an observable class instead of a swiftdata class
I would greatly appreciate if anyone knows what exactly is going on here.
Tested using
XCode Version 16.4 (16F6),
iPhone 16 Pro iOS 18.5 Simulator and
iPhone 15 Pro iOS 18.5 real device.
import SwiftUI
import SwiftData
@Model class Item {
var name: String
init(name: String) {
self.name = name
}
}
struct DuplicateKeysErrorView: View {
@Environment(\.modelContext) private var modelContext
@Query(sort: \Item.name) private var items: [Item]
@State var selection: Item? = nil
var body: some View {
List {
Picker("Picker", selection: $selection) {
Text("Nil").tag(nil as Item?)
ForEach(items) { item in
Text(item.name).tag(item)
}
}
.pickerStyle(.menu)
Button("Add 5 items") {
modelContext.insert(Item(name: UUID().uuidString))
modelContext.insert(Item(name: UUID().uuidString))
modelContext.insert(Item(name: UUID().uuidString))
modelContext.insert(Item(name: UUID().uuidString))
modelContext.insert(Item(name: UUID().uuidString))
}
}
.onAppear {
try! modelContext.delete(model: Item.self)
}
}
}
#Preview {
DuplicateKeysErrorView()
.modelContainer(for: Item.self)
}
We are trying to solve for the following condition with SwiftData + CloudKit:
Lots of data in CloudKit
Perform "app-reset" to clear data & App settings and start fresh.
Reset data models with try modelContext.delete(model:_) myModel.count() confirms local deletion (0 records); but iCloud Console shows expectedly slow process to delete.
Old CloudKit data is returning during the On Boarding process.
Questions:
• Would making a new iCloud Zone for each reset work around this, as the new zone would be empty? We're having trouble finding details about how to do this with SwiftData.
• Would CKSyncEngine have a benefit over the default SwiftData methods?
Open to hearing if anyone has experienced a similar challenge and how you worked around it!
Greetings i have an app that uses three different SwiftData models and i want to know what is the best way to use the them accross the app. I though a centralized behaviour and i want to know if it a correct approach.First let's suppose that the first view of the app will load the three models using the @Enviroment that work with @Observation. Then to other views that add data to the swiftModels again with the @Environment. Another View that will use the swiftData models with graph and datas for average and min and max.Is this a corrent way? or i should use @Query in every view that i want and ModelContext when i add the data.
@Observable
class CentralizedDataModels {
var firstDataModel: [FirstDataModel] = []
var secondDataModel: [SecondDataModel] = []
var thirdDataModel: [ThirdDataModel] = []
let context: ModelContext
init(context:ModelContext) {
self.context = context
}
}
I have used core data before via the model editor. This is the first time I'm using swift data and that too with CloudKit. Can you tell me if the following model classes are correct?
I have an expense which can have only one sub category which in turn belongs to a single category. Here are my classes...
// Expense.swift
// Pocket Expense Diary
//
// Created by Neerav Kothari on 16/05/25.
//
import Foundation
import SwiftData
@Model
class Expense {
@Attribute var expenseDate: Date? = nil
@Attribute var expenseAmount: Double? = nil
@Attribute var expenseCategory: Category? = nil
@Attribute var expenseSubCategory: SubCategory? = nil
var date: Date {
get {
return expenseDate ?? Date()
}
set {
expenseDate = newValue
}
}
var amount: Double{
get {
return expenseAmount ?? 0.0
}
set {
expenseAmount = newValue
}
}
var category: Category{
get {
return expenseCategory ?? Category.init(name: "", icon: "")
}
set {
expenseCategory = newValue
}
}
var subCategory: SubCategory{
get {
return expenseSubCategory ?? SubCategory.init(name: "", icon: "")
}
set {
expenseSubCategory = newValue
}
}
init(date: Date, amount: Double, category: Category, subCategory: SubCategory) {
self.date = date
self.amount = amount
self.category = category
self.subCategory = subCategory
}
}
//
// Category.swift
// Pocket Expense Diary
//
// Created by Neerav Kothari on 16/05/25.
//
import Foundation
import SwiftData
@Model
class Category {
@Attribute var categoryName: String? = nil
@Attribute var categoryIcon: String? = nil
var name: String {
get {
return categoryName ?? ""
}
set {
categoryName = newValue
}
}
var icon: String {
get {
return categoryIcon ?? ""
}
set {
categoryIcon = newValue
}
}
@Relationship(inverse: \Expense.expenseCategory) var expenses: [Expense]? = []
init(name: String, icon: String) {
self.name = name
self.icon = icon
}
}
// SubCategory.swift
// Pocket Expense Diary
//
// Created by Neerav Kothari on 16/05/25.
//
import Foundation
import SwiftData
@Model
class SubCategory {
@Attribute var subCategoryName: String? = nil
@Attribute var subCategoryIcon: String? = nil
var name: String {
get {
return subCategoryName ?? ""
}
set {
subCategoryName = newValue
}
}
var icon: String {
get {
return subCategoryIcon ?? ""
}
set {
subCategoryIcon = newValue
}
}
@Relationship(inverse: \Expense.expenseSubCategory) var expenses: [Expense]? = []
init(name: String, icon: String) {
self.name = name
self.icon = icon
}
}
The reason why I have wrappers is the let the existing code (before CloudKit was integrated), work.
In future versions I plan to query expenses even via category or sub category. I particularly doubt for the relationship i have set. should there be one from category to subcategory as well?
Hi, I am building an iOS app with SwiftUI and SwiftData for the first time and I am experiencing a lot of difficulty with this error:
Thread 44: Fatal error: Never access a full future backing data - PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(backing: SwiftData.PersistentIdentifier.PersistentIdentifierBacking.managedObjectID(<ID> <x-coredata://<UUID>/MySwiftDataModel/p1>)), backing: SwiftData.PersistentIdentifier.PersistentIdentifierBacking.managedObjectID(<ID> <x-coredata://<UUID>/MySwiftDataModel/p1>)) with Optional(<UUID>)
I have been trying to figure out what the problem is, but unfortunately I cannot find any information in the documentation or on other sources online. My only theory about this error is that it is somehow related to fetching an entity that has been created in-memory, but not yet saved to the modelContext in SwiftData.
However, when I am trying to debug this, it's not clear this is the case. Sometimes the error happens, sometimes it doesn't. Saving manually does not always solve the error.
Therefore, it would be extremely helpful if someone could explain what this error means and whether there are any best practices to do with SwiftData, or some pitfalls to avoid (such as wrapping my model context into a repository class).
To be clear, this problem is NOT related to one area of my code, it happens throughout my app, at unpredictable places and time. Given that there is very little information related to this error, I am at a loss at how to make sure that this never happens.
This question has been asked on the forum here as well as on StackOverflow, Reddit (can't link that here), but none of the answers worked for me.
For reference, my models generally look like this:
import Foundation
import SwiftData
@Model
final class MySwiftDataModel {
// Stable cross-device identity
@Attribute(.unique)
var uuid: UUID
var someNumber: Int
var someString: String
@Relationship(deleteRule: .nullify, inverse: \AnotherSwiftDataModel.parentModel)
var childModels: [AnotherSwiftDataModel]
init(uuid: UUID = UUID(), someNumber: Int = 1, someString: String = "Some", childModels: [AnotherSwiftDataModel] = []) {
self.uuid = uuid
self.someNumber = someNumber
self.someString = someString
self.childModels = childModels
}
func addChildModel(model: AnotherSwiftDataModel) {
self.childModels.append(model)
}
func removeChildModel(by id: PersistentIdentifier) {
self.childModels = self.childModels.filter { $0.id != id }
}
}
and the child model:
import Foundation
import SwiftData
@Model
final class AnotherSwiftDataModel {
// Stable cross-device identity
@Attribute(.unique)
var uuid: UUID
var someNumber: Int
var someString: String
var parentModel: MySwiftDataModel?
init(uuid: UUID = UUID(), someNumber: Int = 1, someString: String = "Some") {
self.uuid = uuid
self.someNumber = someNumber
self.someString = someString
}
}
For now, you can assume I am not using CloudKit - i know for a fact the error is unrelated to CloudKit, because it happens when I am not using CloudKit (so I do not need to follow CloudKit's requirements for model design, such as nullable values etc).
As I said, the error surfaces at different times - sometimes during assignments, a lot of times during deletions of related models, etc.
Could you please explain what I am doing wrong and how I can make sure that this error does not happen? What are the architectural patterns that work best for SwiftData in this case? Do you have any examples of things I should avoid?
Thanks
Hello, thank you Apple for supporting custom store with SwiftData and the Schema type is superb to work with. I have successfully set one up with SQL and have some feedback and issues regarding its APIs.
There’s a highlighted message in the documentation about not using internal restricted symbols directly, but they contradict with the given protocols and I am concerned about breaking any App Store rules. Are we allowed to use these? If not, they should be opened up as they’re useful.
BackingData is required to set up custom snapshots, initialization, and getting/setting values. And I want to use it with createBackingData() to directly initialize instances from snapshots when transferring them between server and client or concurrency.
RelationshipCollection for casting to-many relationships from backing data or checking if an array contains a PersistentModel.
SchemaProperty for type erasure in a collection.
Schema.Relationship has KeyPath properties, but it is missing for Schema.Attribute and Schema.CompositeAttribute. Which means you can’t purely depend on the schema to map data. I am unable to access the properties of a custom struct type in a predicate unless I use Mirror with schemaMetadata() or CustomStringConvertible on the KeyPath directly to extract it.
Trivial, but… the KeyPath property name is inconsistent (it’s all lowercase).
It would be nice to retrieve property names from custom struct types, since you are unable access CodingKeys that are auto synthesized by Codable for structs. But I recently realized they’re a part Schema.CompositeAttribute, however I don’t know how to match these without the KeyPath…
I currently map my entities using CodingKeys to their PredicateCodableKeyPathProviding.… but I wish for a simpler alternative!
It’s unclear how to provide the schema to the snapshot before new models are created.
I currently use a static property, but I want to make it flexible if more schemas and configurations are added later on.
I considered saving and loading the schema in a temporary location, but doubtful that the KeyPath values will be available as they are not Codable.
I suspect schemaMetadata() has the information I need to map the backing data without a schema for snapshots, but as mentioned previously, properties are inaccessible…
Allow access to entity metatypes, like value types from SchemaProperty. They’re useful for getting data out of snapshots and casting them to CodingKeys and PredicateCodableKeyPathProviding. They do not carry over when you provide them in the Schema.
I am unable to retrieve the primary key from PersistentIdentifier.
It seems like once you create one, you can’t get it out, like the DataStoreConfiguration in ModelContainer is not the one you used to set it up. I cannot cast it, it is an entirely different struct?
I have to use JSONSerialization to extract it, but I want to get it directly since it is not a column in my database. It is transformed when it goes to/from my tables.
It’s unknown how to support some schema options, such as Spotlight and CloudKit.
Allow for extending macro options, such as adding options to set as primary key, whether to auto increment, etc…
You can create a schema for super and sub entities, but it doesn’t appear you can actually set them up from the @Model macro or use inheritance on these models…
SwiftData history tracking seems incomplete for HistoryDelete, because that protocol requires HistoryTombstone, but this type cannot be instantiated, nor does it contain anything useful to infer from.
As an aside, I want to create my own custom ModelActor that is a global actor. However, I’m unable to replicate the executor that Apple provides where the executor has a ModelContext, because this type does not conform to Sendable. So how did Apple do this? The documentation doesn’t mention unchecked Sendable, but I figure if the protocol is available then we would be able to set up our own.
And please add concurrency features!
Anyway, I hope for more continued support in the future and I am looking forward to what’s new this WWDC! 😊
Hi,
I am developing a Screen Time App and I am having issues with the ShieldConfigurationExtension (ShieldConfigurationDataSource). I know this extensions is sandboxed but I should be able to read data from the main app.
I am using SwiftData as my database, but I am unable to initialize it in the extensions with an error indicating insufficient file permissions. I have App Group set up and I am able to share data using UserDefaults but that is just inconvenient.
Is there any way I could just open the SwiftData in read only mode so that I could display the user some info on the shield?
SwiftData Init:
private func setupContainer() throws {
let schema = Schema([
DogEntity.self,
HouseEntity.self
])
// Use app group container if available
let config: ModelConfiguration
if let containerURL = FileManager.default.containerURL(
forSecurityApplicationGroupIdentifier: "group.\(Bundle.app.bundleIdentifier ?? "")"
) {
config = ModelConfiguration(schema: schema, url: containerURL.appendingPathComponent("default.sqlite"))
} else {
config = ModelConfiguration(schema: schema)
}
self.container = try ModelContainer(for: schema, configurations: [config])
}
Error in extension:
fault: Attempt to add read-only file at path file:///private/var/mobile/Containers/Shared/AppGroup/51431199-5919-4AE6-940C-6FE3C53EEB46/default.sqlite read/write. Adding it read-only instead. This will be a hard error in the future; you must specify the NSReadOnlyPersistentStoreOption.
error: (3) access permission denied
error: Encountered exception error during prepareSQL for SQL string 'SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'Z_METADATA'' : access permission denied with userInfo {
NSFilePath = "/private/var/mobile/Containers/Shared/AppGroup/51431199-5919-4AE6-940C-6FE3C53EEB46/default.sqlite";
NSSQLiteErrorDomain = 3;
} while checking table name from store: <NSSQLiteConnection: 0x154100300>
error: Store failed to load. <NSPersistentStoreDescription: 0x15402d590> (type: SQLite, url: file:///private/var/mobile/Containers/Shared/AppGroup/51431199-5919-4AE6-940C-6FE3C53EEB46/default.sqlite) with error = Error Domain=NSCocoaErrorDomain Code=256 "The file “default.sqlite” couldn’t be opened." UserInfo={NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/51431199-5919-4AE6-940C-6FE3C53EEB46/default.sqlite, NSSQLiteErrorDomain=3} with userInfo {
NSFilePath = "/private/var/mobile/Containers/Shared/AppGroup/51431199-5919-4AE6-940C-6FE3C53EEB46/default.sqlite";
NSSQLiteErrorDomain = 3;
}
Any help appreciated 🙂
Topic:
App & System Services
SubTopic:
General
Tags:
Family Controls
Managed Settings
Screen Time
SwiftData
I am following Apple's instruction to sync SwiftData with CloudKit. While initiating the ModelContainer, right after removing the store from Core Data, the error occurs:
FAULT: NSInternalInconsistencyException: This NSPersistentStoreCoordinator has no persistent stores (unknown). It cannot perform a save operation.; (user info absent)
I've tried removing default.store and its related files/folders before creating the ModelContainer with FileManager but it does not resolve the issue. Isn't it supposed to create a new store when the ModelContainer is initialized? I don't understand why this error occurs. Error disappears when I comment out the #if DEBUG block.
Code:
import CoreData
import SwiftData
import SwiftUI
struct InitView: View {
@Binding var modelContainer: ModelContainer?
@Binding var isReady: Bool
@State private var loadingDots = ""
@State private var timer: Timer?
var body: some View {
VStack(spacing: 16) {
Text("Loading\(loadingDots)")
.font(.title2)
.foregroundColor(.gray)
}
.padding()
.onAppear {
startAnimation()
registerTransformers()
let config = ModelConfiguration()
let newContainer: ModelContainer
do {
#if DEBUG
// Use an autorelease pool to make sure Swift deallocates the persistent
// container before setting up the SwiftData stack.
try autoreleasepool {
let desc = NSPersistentStoreDescription(url: config.url)
let opts = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.my-container-identifier")
desc.cloudKitContainerOptions = opts
// Load the store synchronously so it completes before initializing the
// CloudKit schema.
desc.shouldAddStoreAsynchronously = false
if let mom = NSManagedObjectModel.makeManagedObjectModel(for: [Page.self]) {
let container = NSPersistentCloudKitContainer(name: "Pages", managedObjectModel: mom)
container.persistentStoreDescriptions = [desc]
container.loadPersistentStores { _, err in
if let err {
fatalError(err.localizedDescription)
}
}
// Initialize the CloudKit schema after the store finishes loading.
try container.initializeCloudKitSchema()
// Remove and unload the store from the persistent container.
if let store = container.persistentStoreCoordinator.persistentStores.first {
try container.persistentStoreCoordinator.remove(store)
}
}
// let fileManager = FileManager.default
// let sqliteURL = config.url
// let urls: [URL] = [
// sqliteURL,
// sqliteURL.deletingLastPathComponent().appendingPathComponent("default.store-shm"),
// sqliteURL.deletingLastPathComponent().appendingPathComponent("default.store-wal"),
// sqliteURL.deletingLastPathComponent().appendingPathComponent(".default_SUPPORT"),
// sqliteURL.deletingLastPathComponent().appendingPathComponent("default_ckAssets")
// ]
// for url in urls {
// try? fileManager.removeItem(at: url)
// }
}
#endif
newContainer = try ModelContainer(for: Page.self,
configurations: config) // ERROR!!!
} catch {
fatalError(error.localizedDescription)
}
modelContainer = newContainer
isReady = true
}
.onDisappear {
stopAnimation()
}
}
private func startAnimation() {
timer = Timer.scheduledTimer(
withTimeInterval: 0.5,
repeats: true
) { _ in
updateLoadingDots()
}
}
private func stopAnimation() {
timer?.invalidate()
timer = nil
}
private func updateLoadingDots() {
if loadingDots.count > 2 {
loadingDots = ""
} else {
loadingDots += "."
}
}
}
import CoreData
import SwiftData
import SwiftUI
@main
struct MyApp: App {
@State private var modelContainer: ModelContainer?
@State private var isReady: Bool = false
var body: some Scene {
WindowGroup {
if isReady, let modelContainer = modelContainer {
ContentView()
.modelContainer(modelContainer)
} else {
InitView(modelContainer: $modelContainer, isReady: $isReady)
}
}
}
}
Hi all,
I’m encountering a consistent issue with SwiftData on watchOS when using CloudKit sync. After enabling:
let config = ModelConfiguration(schema: schema, cloudKitDatabase: .automatic)
…the app terminates ~30–60 seconds into a WKExtendedRuntimeSession. This happens specifically when:
Always-On Display is OFF
The iPhone is disconnected or in Airplane Mode
The app is running in a WKExtendedRuntimeSession (e.g., used for meditation tracking)
The Xcode logs show a warning:
Background Task ("CoreData: CloudKit Setup"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination.
It appears CloudKit sync setup is being triggered automatically and flagged by the system as an unmanaged long-running task, leading to termination.
Workaround:
Switching to:
let config = ModelConfiguration(schema: schema, cloudKitDatabase: .none)
…prevents the issue entirely — no background task warning, no crash.
Feedback ID submitted: FB17685611
Just wanted to check if others have seen this behavior or found alternative solutions. It seems like something Apple may need to address in SwiftData’s CloudKit handling on watchOS.
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
CloudKit
watchOS
Background Tasks
SwiftData
My project is using swiftData and I want to implement iCloud sync in it. Now, my data base doesnt have any optional attributes or relationships and CloudKit wants them to be optional.
So, rather than editing all code with unwrapping code for the optionals, how can I provide a bridge that does so in the last stage of actually saving to the store? Sort of, capture it in a proxy object before writing and after reading from the store.
Is there a neat way that can save a lot of debugging? I have code snippets from chat gpt and they are hard to debug. This is my first project in swiftUI.
Thanks.
Neerav
Issue with SwiftData: “no such table: ZAPPSETTINGS” and SQLite I/O error on app launch
Hello,
I’m encountering persistent errors with SwiftData in my SwiftUI app related to Core Data’s underlying SQLite database. Despite defining my models correctly, the app fails to initialize the persistent store, throwing the following error on startup:
CoreData error: SQLCore dispatchRequest: no such table: ZAPPSETTINGS. I/O error opening database at /.../default.store. SQLite error code:1, NSSQLiteErrorDomain=1.
File “default.store” couldn’t be opened.
Context
The error only appears concerning my AppSettings model.
I have another model, LocationPoint, which appears correctly defined and used.
I have tried deleting the app, resetting the device, and cleaning builds but the error persists.
The error message suggests the database file is present but the table for ZAPPSETTINGS (the Core Data table for AppSettings) does not exist.
Code Samples
Main App Entry
import SwiftData
import SwiftUI
@main
struct Krow3_0App: App {
@State private var userLocationManager = UserLocationManager()
@State private var geocodingViewModel = GeocodingViewModel()
@State private var locationSearchViewModel = LocationSearchViewModel()
@State private var router = Router()
var body: some Scene {
WindowGroup {
LaunchView()
.environment(userLocationManager)
.environment(geocodingViewModel)
.environment(locationSearchViewModel)
.environment(router)
.modelContainer(for: [LocationPoint.self, AppSettings.self])
}
}
}
AppSettings Model
import Foundation
import SwiftData
@Model
class AppSettings {
var isMetric: Bool
init(isMetric: Bool = false) {
self.isMetric = isMetric
}
}
What I’ve Tried
Fully uninstalling and reinstalling the app on device and simulator.
Resetting the simulator/device.
Cleaning the Xcode build folder.
Verifying the schema logs which correctly list both LocationPoint and AppSettings.
Changing model names to avoid potential conflicts.
Adding .modelContainer configuration with autosave enabled.
Questions
Is there a known bug or limitation with SwiftData concerning certain model setups or naming?
Could this be related to how the data container initializes or migrates schemas?
Are there recommended debugging or migration steps to resolve “no such table” SQLite errors with SwiftData?
How can I safely reset or migrate the persistent store without corrupting the database?
Any insights or suggestions would be greatly appreciated!
Thank you!